package com.bookhouse.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.bookhouse.dao.BaseDAO;
import com.bookhouse.dao.DAOException;
import com.bookhouse.dao.MenuDAO;
import com.bookhouse.domain.Menu;

public class MenuDAOImpl extends BaseDAO implements MenuDAO{

	private static final String GET_MENU_SQL = "select a.id as id1,a.name as name1,a.display as display1,b.id as id2,b.name as name2,b.display as display2 "
			+ "from menu a,menu b where b.parentId = a.id and a.parentId =?";

	@Override
	public List<Menu> getMenu() throws DAOException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Menu> list = new ArrayList<Menu>();
		try {
			conn = getConnection();
			ps = conn.prepareStatement(GET_MENU_SQL);
			ps.setInt(1, 0);
			rs = ps.executeQuery();
			int preId = 0;
			int preId1 = 0;
			Menu menu = null;
			Menu subCat = null;
			while (rs.next()) {
				if (rs.getInt("id1") != preId) { // ��һ���µ�һ���ڵ�
					preId = rs.getInt("id1");
					menu = new Menu();
					menu.setId(rs.getInt("id1"));
					menu.setParentId(0);
					menu.setName(rs.getString("name1"));
					menu.setDisplay(rs.getString("display1"));
					menu.setList(new ArrayList<Menu>());
					list.add(menu);
				}
				if (rs.getInt("id2") != preId1) {
					preId1 = rs.getInt("id2");
					subCat = new Menu(); // �����ڵ�
					subCat.setId(rs.getInt("id2"));
					subCat.setParentId(rs.getInt("id1"));
					subCat.setName(rs.getString("name2"));
					subCat.setDisplay(rs.getString("display2"));
					subCat.setList(new ArrayList<Menu>());
					menu.getList().add(subCat);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return list;
	}

}
